<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="线路名称" prop="lineName">
        <el-input
          v-model="queryParams.lineName"
          placeholder="请输入线路名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="线路类别" prop="lineType">
        <el-select v-model="queryParams.lineType" placeholder="请选择线路类别" clearable size="small">
          <el-option
            v-for="dict in lineTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="isShowOperate">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['patrol:line:add']"
        >新增
        </el-button>
      </el-col>
      <!--	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="lineList" @selection-change="handleSelectionChange" style="color: #333333"
              :header-cell-style="{background:'#E3E3E3'}">
      <el-table-column label="学校名称" align="center" prop="school.name" v-if="!isShowOperate"/>
      <el-table-column label="学校类别" align="center" prop="school.type" :formatter="schoolTypeFormat"
                       v-if="!isShowOperate"/>
      <el-table-column label="线路名称" align="center" prop="lineName"/>
      <el-table-column label="巡逻点位" align="center" prop="lineSites" :formatter="sitesFormat"/>
      <el-table-column label="时间段" align="center" prop="lineSites" :formatter="durationFormat"/>
      <el-table-column label="线路类别" align="center" prop="lineType" width="80" :formatter="lineTypeFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            v-if="isShowOperate"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['patrol:line:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            v-if="isShowOperate"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['patrol:line:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            v-if="isShowOperate"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            v-if="isShowOperate"
            icon="el-icon-document-copy"
            @click="handleCopy(scope.row)"
            v-hasPermi="['patrol:line:add']"
          >复制线路
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="initMap(scope.row)"
          >查看线路详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改巡查线路对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form style="max-height: 400px;overflow: auto;overflow-x: hidden" ref="form" :model="form" :rules="rules"
               label-width="100px" :disabled="isView">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="线路名称" prop="lineName">
              <el-input v-model="form.lineName" placeholder="请输入线路名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路类别" prop="lineType">
              <el-select v-model="form.lineType" placeholder="请选择线路类别" @change="change()">
                <el-option
                  v-for="dict in lineTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-row v-for="(lineSite, index) in form.lineSites">
            <el-form-item :label="'巡逻点位'+(index+1)">
              <el-col :span="6">
                <el-form-item :prop="'lineSites['+index+'].siteId'" label-width="0"
                              :rules="{required: true, message: '巡逻点位不能为空', trigger: ['change']}">
                  <el-select v-model="lineSite.siteId" placeholder="请选择学校巡逻点位" @change="change()">
                    <el-option
                      v-for="site in siteOptions"
                      :key="site.id"
                      :label="site.siteName"
                      :value="site.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>


              <el-col :span="10">
                <el-form-item :prop="'lineSites['+index+'].range'" label-width="0"
                              :rules="{required: true, message: '起止时间不能为空', trigger: ['change']}">
                  <el-time-picker style="width: 315px;"
                                  format="HH:mm"
                                  value-format="HH:mm"
                                  start-placeholder="请选择起始时间"
                                  end-placeholder="请选择终止时间"
                                  range-separator="至"
                                  is-range
                                  :picker-options="pickerTime"
                                  v-model="lineSite.range"
                                  @input="change"
                                  placeholder="截止时间">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="!isView">
                <el-button type="primary" plain icon="el-icon-arrow-up" @click.prevent="upSite(index)"></el-button>
                <el-button type="primary" plain icon="el-icon-arrow-down" @click.prevent="downSite(index)"></el-button>
                <el-button type="danger" plain @click.prevent="removeSite(index)">删除</el-button>
              </el-col>
            </el-form-item>
          </el-row>
        </el-row>

        <!--动态添加巡逻点位-->
        <el-row>
          <el-form-item label="">
            <el-col :span="3">
              <el-button style="border: 1px solid #1E8BFC;color: #1E8BFC;" icon="el-icon-plus" @click="addSite"
                         v-if="!isView">添加巡逻点位
              </el-button>
            </el-col>
          </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" v-if="!isView">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="线路地点" :visible.sync="gpsview" append-to-body center>
      <div id="container"/>
    </el-dialog>
  </div>
</template>

<script>
import {listLine, getLine, delLine, addLine, updateLine, exportLine} from "@/api/patrol/line";
import {checkPermi} from "@/utils/permission";
import {listSiteAll} from "@/api/patrol/site";
import AMapLoader from "@amap/amap-jsapi-loader";

window._AMapSecurityConfig = {
  securityJsCode: '47f39bbd3f47b91d1cbb2311453a0b4e',
}

export default {
  name: "Line-name",
  data() {
    return {
      gpsview: false,
      pickerTime: {
        selectableRange: this.firstTime + " - 24:00"
      },
      firstTime: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡查线路表格数据
      lineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 线路类别字典
      lineTypeOptions: [],

      // 巡逻点位和巡逻点位关系
      siteOptions: [],
      isView: false,
      lineSites: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lineName: null,
        lineType: null,
        schoolId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lineName: [
          {required: true, message: "线路名称不能为空", trigger: "blur"}
        ],
        lineType: [
          {required: true, message: "线路类别不能为空", trigger: ["blur", "change"]}
        ],
      },
      // 地图相关
      map: null,
      marker: null,
      gps: {
        name: [],
        dian: [],
        itme: []
      },
    };
  },
  computed: {
    isShowOperate: function () {
      return checkPermi(['patrol:guard:edit']);
    },
  },
  created() {
    let schoolInfo = this.$route.query.schoolInfo;
    if (schoolInfo) {
      this.queryParams.schoolId = schoolInfo.id;
    }
    this.queryParams.lineType = this.$route.query.lineType;
    this.getPatrolTypeOptions();
    this.getSchoolTypeOptions();
    this.getSiteOptions();
    this.getList();
    this.initgps();
  },
  methods: {
    change(val) {
      this.form = {...this.form};
    },
    getSiteOptions() {
      this.loading = true;
      listSiteAll().then(response => {
        this.siteOptions = response.data;
        this.loading = false;
      });
    },
    getSchoolTypeOptions() {
      this.loading = true;
      this.getDicts("shool_type").then(response => {
        this.schoolTypeOptions = response.data;
        this.loading = false;
      });
    },
    getPatrolTypeOptions() {
      this.loading = true;
      this.getDicts("patrol_type").then(response => {
        this.lineTypeOptions = response.data;
        this.loading = false;
      });
    },

    // 动态添加和删除巡逻点位
    addSite() {
      this.form.lineSites.push({
        siteId: null,
        siteOrder: this.form.lineSites.length
      });
    },
    removeSite(index) {
      if (this.form.lineSites.length == 1) {
        this.msgError("请保留至少一个巡逻点位");
        return;
      }
      if (index !== -1) {
        this.form.lineSites.splice(index, 1);
      }
    },
    upSite(index) {
      if (index == 0) {
        alert("已经是第一个巡逻点位了！");
        return;
      }

      var tempRange = this.form.lineSites[index - 1].range;
      this.form.lineSites[index - 1].range = this.form.lineSites[index].range;
      this.form.lineSites[index].range = tempRange;

      var temp = this.form.lineSites[index - 1];
      this.form.lineSites.splice(index - 1, 1);
      this.form.lineSites.splice(index, 0, temp);
      this.form.lineSites[index - 1].siteOrder = index - 1;
      this.form.lineSites[index].siteOrder = index;
    },
    downSite(index) {
      if (index == this.form.lineSites.length - 1) {
        alert("已经是最后一个巡逻点位了！");
        return;
      }

      var tempRange = this.form.lineSites[index].range;
      this.form.lineSites[index].range = this.form.lineSites[index + 1].range;
      this.form.lineSites[index + 1].range = tempRange;

      var temp = this.form.lineSites[index];
      this.form.lineSites.splice(index, 1);
      this.form.lineSites.splice(index + 1, 0, temp);
      this.form.lineSites[index].siteOrder = index;
      this.form.lineSites[index + 1].siteOrder = index + 1;
    },

    /** 查询巡查线路列表 */
    getList() {
      this.loading = true;
      listLine(this.queryParams).then(response => {
        this.lineList = response.rows;
        console.log(this.lineList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 线路类别字典翻译
    lineTypeFormat(row, column) {
      return this.selectDictLabel(this.lineTypeOptions, row.lineType);
    },
    schoolTypeFormat(row, column) {
      return this.selectDictLabel(this.schoolTypeOptions, row.school.type);
    },
    sitesFormat(row, column) {  //巡逻点位id转化为巡逻点位名称，并拼接起来
      let idNameMap = {};
      row.sites.forEach(e => {
        idNameMap[e.id] = e.siteName;
      });
      let siteNameString = "";
      row.lineSites.forEach(item => {
        siteNameString += idNameMap[item.siteId] + ",";
      });
      return siteNameString.substring(0, siteNameString.length - 1);
    },
    durationFormat(row, column) { //时间段格式化
      return row.lineSites[0].startTime + "-" + row.lineSites[row.lineSites.length - 1].finishTime;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        lineName: null,
        lineType: null,
        schoolId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        lineSites: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isView = false;
      this.reset();

      getLine().then(response => {

        this.title = "添加巡查线路";
        //动态添加巡逻点位
        this.form = response.data;
        this.form.lineSites = response.lineSites;
        this.form.lineType = null; //点击查看路线后再点击新增，红色提示“路线类别不能为空”--问题解决

        this.form.lineSites.push({
          siteId: null,
          siteOrder: this.form.lineSites.length
        });

        this.open = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isView = false;
      this.reset();

      const id = row.id || this.ids
      getLine(id).then(response => {
        this.open = true;
        this.title = "修改巡查线路";

        this.form = response.data;
        this.form.lineSites = response.lineSites;
        this.convertTimes2Range();
      });
    },
    handleView(row) {  //查看线路
      this.reset();
      const id = row.id || this.ids
      getLine(id).then(response => {
        this.form = response.data;
        this.form.lineSites = response.lineSites;
        this.convertTimes2Range();

        this.open = true;
        this.title = "查看巡查线路";

        this.isView = true;
      });
    },
    handleCopy(row) {  //复制线路
      this.reset();
      const id = row.id || this.ids
      getLine(id).then(response => {
        this.form = response.data;
        this.form.id = null; //复制线路为新增线路，需要去掉ID。
        this.open = true;
        this.title = "复制巡查线路";
        this.convertTimes2Range();

        this.isView = false;
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        console.log(valid);
        if (valid) {
          this.convertRange2Times();
          if (!this.checkTime()) {
            return;
          }
          if (this.form.id != null) {
            updateLine(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLine(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.resetQuery();
            });
          }
        }
      });
    },
    convertTimes2Range() {
      this.form.lineSites.forEach(item => {
        let arr = new Array(2);
        arr[0] = item.startTime;
        arr[1] = item.finishTime;
        item.range = arr;
      });
    },
    convertRange2Times() {
      this.form.lineSites.forEach(item => {
        if (item.range == null) {
          // this.msgError("请查看确保每个时间不为空");
          return false;
        }
        item.startTime = item.range[0];
        item.finishTime = item.range[1];
      });
    },
    checkTime() {
      let startTimes = new Array(this.form.lineSites.length);
      let finishTimes = new Array(this.form.lineSites.length);
      let now = new Date();
      for (let i = 0; i < this.form.lineSites.length; i++) {
        startTimes[i] = this.form.lineSites[i].startTime;
        finishTimes[i] = this.form.lineSites[i].finishTime;
        if (startTimes[i] == null || finishTimes[i] == null) {
          return false;
        }
        if (i > 0 && (this.parseTime(startTimes[i]) < this.parseTime(startTimes[i - 1]) || this.parseTime(finishTimes[i]) < this.parseTime(finishTimes[i - 1]))) {
          this.msgError("请检查确保下一个巡逻点位的开始/结束时间晚于上一个巡逻点位对应的开始/结束时间");
          return false;
        }
      }
      return true;
    },
    parseTime(minuteSecond) {
      return parseInt((minuteSecond.split(":"))[0]) * 60 + parseInt(minuteSecond.split(":")[1]);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除所选数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      }).then(function () {
        return delLine(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    initgps() {
      AMapLoader.load({
        "key": "a423874b07f076758138f4d36f6f74df",
        "version": "2.0",
        "plugins": [
          "AMap.Scale",
          "AMap.HawkEye",
          'AMap.MapType',
        ]
      }).then((AMap) => {
        this.map = new AMap.Map('container', {
          viewMode: "2D",
          zoom: 13,
          resizeEnable: true
        });
        this.map.addControl(new AMap.MapType());
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.HawkEye({
          isOpen: true
        }));
      });
    },
    initMap(data) {
      this.gpsview = true;
      this.gps = {
        name: [],
        dian: [],
        itme: []
      };
      data.sites.forEach((e, i) => {
        this.gps.dian.push([parseFloat(e.longitude), parseFloat(e.latitude)]);
        this.gps.name.push(e.siteName);
        this.gps.itme.push(i + 1);
      });
      AMapLoader.load({
        "key": "a423874b07f076758138f4d36f6f74df",
        "version": "2.0",
        "plugins": [
          "AMap.Scale",
          "AMap.HawkEye",
          'AMap.MapType',
        ]
      }).then((AMap) => {
        console.log("=========")
        // 初始化地图
        this.map = new AMap.Map('container', {
          viewMode: "2D",
          zoom: 13,
          // 江北区人民政府
          // center: [106.580323, 29.612549],
          center: this.gps.dian[0],
          resizeEnable: true
        });
        this.map.addControl(new AMap.MapType({defaultType: 1}));
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.HawkEye({
          isOpen: true
        }));
        var lnglats = this.gps.dian;
        var markers = [];
        for (var i = 0; i < lnglats.length; i++) {
          var lnglat = lnglats[i];
          var markerContent = '' +
            '<div class="custom-content-marker" style="text-align: center;width: 30px;height: 30px; background-size: 100% 100%;background-image: url(\'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png\')">' +
            '<span style="color: white">' + this.gps.itme[i] + '</span>' +
            '</div>';

          var marker = new AMap.Marker({
            position: new AMap.LngLat(lnglat[0], lnglat[1]),
            // 将 html 传给 content
            content: markerContent,
            // 以 icon 的 [center bottom] 为原点
            offset: new AMap.Pixel(-13, -30)
          });
          var div = "<div className='info'>" + this.gps.name[i] + "</div>";
          marker.setLabel({
            direction: 'right',
            offset: new AMap.Pixel(-1, 0),  //设置文本标注偏移量
            content: div, //设置文本标注内容
          });
          markers.push(marker);
        }
        var overlayGroups = new AMap.OverlayGroup(markers);
        this.map.add(overlayGroups);
        var polyline = new AMap.Polyline({
          path: this.gps.dian,
          strokeColor: "#3366FF",
          strokeWeight: 6,
          strokeOpacity: 1,
          strokeStyle: "solid",
          strokeDasharray: [10, 5],
          lineJoin: "round",
          lineCap:'square',
          showDir:true
        });
        polyline.setMap(this.map);
        // this.map.on('click', this.addMarker);
        // this.searchMap();
        this.map.setFitView(null, false, [150, 60, 100, 60]);
      }).catch(e => {
        console.log(e);
      });
    },
  }
};
</script>

<style scoped>
#container {
  overflow: hidden;
  width: 100%;
  height: 600px;
  margin: 0;
  font-family: "微软雅黑";
}
</style>

<style>
.amap-marker-label {
  border: 0;
  background-color: transparent;
}
</style>
